<template>
  <div class="employers-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用人单位名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin"
          >
            新增用人单位
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="employers"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="单位名称" />
        <el-table-column prop="address" label="单位地址" show-overflow-tooltip />
        <el-table-column prop="contactPerson" label="联系人" />
        <el-table-column prop="contactPhone" label="联系电话" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用人单位' : '编辑用人单位'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        
        <el-form-item label="单位地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const employers = ref([])

console.log('Employers.vue script setup executed.')

const form = reactive({
  id: null,
  name: '',
  address: '',
  contactPerson: '',
  contactPhone: ''
})

const rules = {
  name: [
    { required: true, message: '请输入单位名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入单位地址', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const fetchEmployers = async () => {
  try {
    loading.value = true
    console.log('Fetching employers...', { currentPage: currentPage.value, pageSize: pageSize.value, searchQuery: searchQuery.value })
    const res = await request.get('api/employers/page', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        name: searchQuery.value
      }
    })
    console.log('Employers fetched successfully:', res)
    employers.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取用人单位列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchEmployers()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployers()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    name: '',
    address: '',
    contactPerson: '',
    contactPhone: ''
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用人单位吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`api/employers/${row.id}`)
    ElMessage.success('删除成功')
    fetchEmployers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'add') {
      await request.post('api/employers', form)
      ElMessage.success('新增成功')
    } else {
      await request.put(`api/employers/${form.id}`, form)
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    fetchEmployers()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  console.log('Employers.vue mounted.')
  fetchEmployers()
})
</script>

<style scoped>
.employers-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 